package yang.itcode.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import yang.itcode.exception.BusinessException;
import yang.itcode.mapper.CategoryMapper;
import yang.itcode.model.pojo.Category;
import yang.itcode.service.CategoryService;
import yang.itcode.utils.ThreadUtil;

import java.beans.Transient;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static yang.itcode.constant.ErrorConstant.CATEGORY_PARAM_EXCEPTION_CODE;
import static yang.itcode.constant.ErrorConstant.CATEGORY_PARAM_EXCEPTION_MESSAGE;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;


    @Override
    public boolean addCategory(JSONObject obj) {
        String name = obj.getStr("name");
        Integer parentId = obj.getInt("parentId");
        Integer sort = obj.getInt("sort");
        Integer userId = ThreadUtil.getCurrentId();
        if (name == null || parentId == null) {
            throw new BusinessException(CATEGORY_PARAM_EXCEPTION_CODE, CATEGORY_PARAM_EXCEPTION_MESSAGE);
        }
        Category category = new Category();
        category.setName(name);
        category.setParentId(parentId);
        category.setSort(sort);
        category.setCreateUserId(userId);
        category.setUpdateUserId(userId);
        return categoryMapper.insert(category) == 1;
    }

    @Override
    public JSONObject getCategoryTree() {
        JSONObject condition = new JSONObject();
        condition.set("status", 1);
        List<Category> categories = categoryMapper.selectByCondition(condition);

        // 构建父子关系映射
        Map<Integer, List<Category>> parentChildMap = new HashMap<>();
        Category rootCategory = null;

        for (Category category : categories) {
            if (category.getId() == 1) {
                // 找到根节点（id=1）
                rootCategory = category;
            } else {
                // 按父ID分组子节点
                parentChildMap.computeIfAbsent(category.getParentId(), k -> new ArrayList<>()).add(category);
            }
        }

        // 对每个父节点的子节点按sort字段排序
        parentChildMap.forEach((parentId, children) ->
            children.sort((c1, c2) -> {
                Integer sort1 = c1.getSort() != null ? c1.getSort() : 0;
                Integer sort2 = c2.getSort() != null ? c2.getSort() : 0;
                return sort1.compareTo(sort2);
            })
        );

        JSONObject result = new JSONObject();
        if (rootCategory != null) {
            result = buildCategoryTree(rootCategory, parentChildMap);
        }

        return result;
    }

    @Override
    public PageInfo<JSONObject> getCategoryList(Integer pageNum, Integer pageSize, JSONObject condition) {
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        condition.set("status", 1);
        List<JSONObject> categories = categoryMapper.selectCategoryView(condition);
        return new PageInfo<>(categories);
    }

    @Override
    public boolean updateCategory(JSONObject obj) {
        String name = obj.getStr("name");
        Integer parentId = obj.getInt("parentId");
        Integer sort = obj.getInt("sort");
        Integer id = obj.getInt("id");
        if (name == null || parentId == null) {
            throw new BusinessException(CATEGORY_PARAM_EXCEPTION_CODE, CATEGORY_PARAM_EXCEPTION_MESSAGE);
        }
        Integer userId = ThreadUtil.getCurrentId();
        Category category = new Category();
        category.setId(id);
        category.setName(name);
        category.setParentId(parentId);
        category.setSort(sort);
        category.setUpdateUserId(userId);
        return categoryMapper.update(category) == 1;
    }

    @Override
    @Transient
    public boolean deleteCategory(Integer id) {
        Integer userId = ThreadUtil.getCurrentId();
        Category category = new Category();
        category.setId(id);
        category.setStatus(0);
        category.setUpdateUserId(userId);
        boolean deleteResult =  categoryMapper.update(category) == 1;
        if (deleteResult) {
            // 级联删除子分类
            JSONObject condition = new JSONObject();
            condition.set("status", 1);
            condition.set("parentId", id);
            List<Category> childCategories = categoryMapper.selectByCondition(condition);
            for (Category child : childCategories) {
                deleteCategory(child.getId());
            }
        }
        return deleteResult;
    }

    /**
     * 根据ID获取节点及其所有子节点
     * @param id 节点ID
     * @return 节点及其所有子节点的列表
     */
    @Override
    public List<Category> getCategoryWithDescendants(Integer id) {
        // 获取所有有效的分类
        JSONObject condition = new JSONObject();
        condition.set("status", 1);
        List<Category> allCategories = categoryMapper.selectByCondition(condition);

        // 构建ID到分类的映射，便于快速查找
        Map<Integer, Category> categoryMap = new HashMap<>();
        for (Category category : allCategories) {
            categoryMap.put(category.getId(), category);
        }

        // 查找目标节点
        Category targetCategory = categoryMap.get(id);
        if (targetCategory == null) {
            return new ArrayList<>(); // 如果找不到目标节点，返回空列表
        }

        // 递归收集所有子节点
        List<Category> result = new ArrayList<>();
        collectDescendants(targetCategory, allCategories, result);

        return result;
    }

    /**
     * 递归构建分类树
     */
    private JSONObject buildCategoryTree(Category category, Map<Integer, List<Category>> parentChildMap) {
        JSONObject node = new JSONObject();
        node.set("id", category.getId());
        node.set("name", category.getName());
        node.set("parentId", category.getParentId());
        node.set("sort", category.getSort());

        // 获取子节点
        List<Category> children = parentChildMap.get(category.getId());
        if (children != null && !children.isEmpty()) {
            JSONArray childrenArray = new JSONArray();
            for (Category child : children) {
                childrenArray.add(buildCategoryTree(child, parentChildMap));
            }
            node.set("children", childrenArray);
        } else {
            node.set("children", new JSONArray());
        }

        return node;
    }

    /**
     * 递归收集节点及其所有子节点
     * @param category 当前节点
     * @param allCategories 所有分类列表
     * @param result 结果列表
     */
    private void collectDescendants(Category category, List<Category> allCategories, List<Category> result) {
        // 添加当前节点到结果中
        result.add(category);

        // 查找并递归处理所有子节点
        for (Category child : allCategories) {
            if (child.getParentId() != null && child.getParentId().equals(category.getId())) {
                collectDescendants(child, allCategories, result);
            }
        }
    }
}
